package api

import (
	"fmt"
	"kyland.com/eagle/lib/etcd"
	"kyland.com/eagle/lib/exception"
	serf "kyland.com/eagle/lib/serf"
	"kyland.com/eagle/manager"
)

func ShareAdd(ctx *Context) {
	name := ctx.paramString("name")
	cid, err := manager.AddShareFile(name)
	if err != nil {
		ctx.jsonFailure(err)
	}

	cli, err := etcd.GetKeysApi()
	if err != nil {
		ctx.jsonFailure(err)
	}

	defer cli.Close()
	err = cli.Set(name, cid)
	if err != nil {
		ctx.jsonFailure("put name, cid failed:%v, %v", name, cid)
	}

	client, err := serf.New()
	if err != nil {
		ctx.jsonFailure(err)
	}

	err = client.Event(serf.FILEEVENT, fmt.Sprintf("%s,%s", name, cid))
	if err != nil {
		ctx.jsonFailure(err)
	}
	//go manager.SendToPeers(name, cid)
	ctx.jsonSuccess(cid)
}

func ShareGet(ctx *Context) {
	share := &manager.Share{}
	ctx.param(share, []R{"cid"}, []R{"path"})
	err := manager.GetShareFile(share)
	if err != nil {
		ctx.jsonFailure(err)
	}
	ctx.jsonSuccess()
}

func GetCidFromFileName(ctx *Context) {
	name := ctx.paramString("name")

	cli, err := etcd.GetKeysApi()
	if err != nil {
		ctx.jsonFailure(err)
	}

	defer cli.Close()
	value, err := cli.Get(name)
	if err != nil {
		ctx.jsonFailure("get cid failed:%v", name)
	}
	ctx.jsonSuccess(value)
}

func FileToPeers(ctx *Context) {
	share := &manager.Share{}
	ctx.param(share, []R{"cid"}, []R{"path"})

	cli, err := etcd.GetKeysApi()
	if err != nil {
		ctx.jsonFailure(err)
	}

	defer cli.Close()
	err = cli.Set(share.Path, share.Cid)
	if err != nil {
		errMsg := fmt.Sprintf("put name, cid failed:%v, %v", share.Path, share.Cid)
		exception.Throw(errMsg)
	}
	ctx.jsonSuccess(share)
}
